package com.bite.blog.controller;

import com.bite.blog.constant.Constants;
import com.bite.blog.model.Result;
import com.bite.blog.model.UserInfo;
import com.bite.blog.service.UserService;
import com.bite.blog.utils.JwtUtils;
import com.bite.blog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.val;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String username, String password) { //返回前端的是token,要统一结果返回 ,前端传入的参数是userName,password
        //1. 参数校验合法性
        //2. 校验密码是否正确
        //3. 密码正确,返回token
        //4. 密码错误,返回错误信息

        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return Result.fail("账号或密码为空");  //Result格式返回
        }

        //从数据库中查找用户
        UserInfo userInfo = userService.selectByName(username);
        //用户不存在
        if (userInfo == null) {
            return Result.fail("用户不存在");
        }
        //密码错误
        /*if (!password.equals(userInfo.getPassword())) {
            return Result.fail("密码错误");
        }*/
        if (!SecurityUtils.verify(password,userInfo.getPassword())){
            return Result.fail("密码错误");
        }

        //密码正确,返回token
        Map<String,Object> claim = new HashMap<>();
        //存入用户信息
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        //生成token
        String token = JwtUtils.genJwtToken(claim);
        return Result.success(token);  //根据key计算token返回给前端
    }


    @RequestMapping("/getUserInfo")  //获取当前用户登录信息,从token里面拿
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token里获取用户信息(之前用户信息已存入token)
        Integer userId = JwtUtils.getIdByToken(token);
        if(userId == null) {
            //用户未登录
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return userInfo;
    }


    /*
    * 根据博客作者ID.获取作者信息
    * */
    @RequestMapping("/getAuthorInfo")  //获取博客作者信息
    public UserInfo getAuthorInfo(Integer blogId){
        //根据博客ID,获取作者ID
        //根据作者ID,获取作者信息
        if(blogId <= 0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        return userInfo;
    }
}
